package com.amtf.datafile3.core.xsv;

import java.io.File;

import com.amtf.datafile3.DataCatalog;
import com.amtf.datafile3.DataException;
import com.amtf.datafile3.DataFile;
import com.amtf.datafile3.DataTableDefinition;
import com.amtf.datafile3.DefinitionException;
import com.amtf.datafile3.cfg.fil.FilDataTableDefinition;
import com.amtf.datafile3.cfg.xsv.XsvDataTableDefinition;

public class XsvDataFile extends DataFile {
	private static final long serialVersionUID = -7200875452550106437L;
	protected int startRow;
	protected boolean firstRowTitle;
	protected String charset;
	protected char delimiter;
	protected char smartQuote;
	protected String filePattern;

	public XsvDataFile(File fileOrDir, String charset, char delimiter, char smartQuote, String filePattern, boolean firstRowTitle) {
		this(fileOrDir, charset, delimiter, smartQuote, filePattern, 0, firstRowTitle);
	}

	public XsvDataFile(File fileOrDir, String charset, char delimiter, char smartQuote, String filePattern, int startRow, boolean firstRowTitle) {
		super(null, fileOrDir);
		this.dataAccessor = new XsvDataAccessor();
		this.charset = charset;
		this.startRow = startRow;
		this.firstRowTitle = firstRowTitle;
		this.delimiter = delimiter;
		this.smartQuote = smartQuote;
		this.filePattern = filePattern;
	}

	public XsvDataFile(DataTableDefinition definition, File fileOrDir, String filePattern) throws DefinitionException {
		super(definition, fileOrDir);
		if (definition != null && !(definition instanceof FilDataTableDefinition)) {
			throw new DefinitionException("Definition must be instance of XsvDataTableDefinition");
		} else {
			this.dataAccessor = new XsvDataAccessor();
			
			XsvDataTableDefinition def = (XsvDataTableDefinition) definition;
			this.charset = def.getCharset();
			this.startRow = def.getStartRow();
			this.firstRowTitle = def.isFirstRowTitle();
			this.delimiter = def.getDelimiter();
			this.smartQuote = def.getQuote();
			this.filePattern = filePattern;
		}
	}

	public DataCatalog openCatalog() throws DataException {
		DataCatalog dc = dataAccessor.open("file:///" + this.getPath() + "?charset=" + charset + "&startRow=" + startRow + "&firstRowTitle=" + firstRowTitle + "&delimiter="
				+ delimiter + "&smartQuote=" + smartQuote + "&filePattern=" + filePattern + "&subFolder=false");
		if (definition != null) {
			dc.setDataTableDefinition(definition);
		}
		return dc;
	}
}
